package com.telewave.stompdemo.conf;

import com.telewave.stompdemo.conf.properties.StompBrokerRelayProperties;
// import com.telewave.stompdemo.interceptors.AuthenticationInterceptor;
import com.telewave.stompdemo.interceptors.GetHeaderParamInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import javax.annotation.Resource;

/**
 * TODO
 *
 * @author looveh
 * @since 2023/10/16 18:00:01
 **/
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Resource
    private StompBrokerRelayProperties stompBrokerRelayProperties;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOrigins("*")
                // .addInterceptors(new AuthenticationInterceptor())
                .setHandshakeHandler(new DefaultHandshakeHandler(new TomcatRequestUpgradeStrategy()));
        // .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // registry.enableSimpleBroker("/topic");
        registry.setUserDestinationPrefix("/user");


        registry.setApplicationDestinationPrefixes("/app");

        registry.enableStompBrokerRelay("/exchange", "/topic")
                // BrokerRelay集群需要提供集群地址
                .setRelayHost(stompBrokerRelayProperties.getHost())
                .setVirtualHost(stompBrokerRelayProperties.getVirtualHost())
                .setClientLogin(stompBrokerRelayProperties.getClientUsername())
                .setClientPasscode(stompBrokerRelayProperties.getClientPassword())
                .setSystemLogin(stompBrokerRelayProperties.getSystemUsername())
                .setSystemPasscode(stompBrokerRelayProperties.getSystemPassword())
                .setSystemHeartbeatSendInterval(stompBrokerRelayProperties.getSystemHeartbeatSendInterval())
                .setSystemHeartbeatReceiveInterval(stompBrokerRelayProperties.getSystemHeartbeatReceiveInterval())
        ;
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new GetHeaderParamInterceptor());
    }

    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.taskExecutor();
    }
}
